package com.yc.spring.aop.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/2
 * Email haijunzhou@hnit.edu.cn
 */
// 基于继承实现
// cglib 动态字节码技术
public class CGLIB {

    public static void main(String[] args) {
        人 person = new 房东();
        人 proxyObject = proxy(person);
        proxyObject.say();
    }

    public static <T> T proxy(T target){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy,
                                    Method method,
                                    Object[] args,
                                    MethodProxy methodProxy) throws Throwable {
                try {
                    System.out.println("前置增强");
                    Object ret = method.invoke(target, args);
                    System.out.println("返回增强");
                    return ret;
                } catch (Exception e) {
                    System.out.println("异常增强");
                    throw new RuntimeException(e);
                } finally {
                    System.out.println("后置增强");
                }
            }
        });
        Object proxyObject = enhancer.create();
        return (T) proxyObject;
    }

}
